var col_defs,ds,tbl, migration_tbl;
var db_env_button,Finalize_Button,Submit_Button ;
var wait_dialog;
var app_timeout = 3500;
YAHOO.util.Event.onDOMReady(function () {
	// Initialize the temporary Panel to display while waiting for external content to load
		 wait_dialog = 
				new YAHOO.widget.Panel("loading_dialog",  
					{ width:"240px", 
					  fixedcenter:true, 
					  close:false, 
					  draggable:false, 
					  zindex:4,
					  modal:true,
					  visible:false
					} 
				);
		wait_dialog.setHeader("Loading, please wait...");
		wait_dialog.setBody('<img src="./images/lib/rel_interstitial_loading.gif" />');
		wait_dialog.render(document.body);		
});

YAHOO.util.Event.onContentReady("model-generator", function() {
	Finalize_Button = new YAHOO.widget.Button("model-finalize",{
		id:"finalize",
		type:"button",
		label:"Finalize &amp; View"
	});
	
	Submit_Button = new YAHOO.widget.Button("model-submit",{
		id:"scaffold",
		type:"button",
		label:"Generate Scaffolding",
		disabled:false
	});
});

YAHOO.util.Event.onContentReady("modelbuilder-info",function () {
	
		var MDL_AutoComplete = {
			handleSuccess:function (o) {
				var tmpArray = o.responseText.replace(/[\s\t\n\r]/,"").split(",");
				
				var dsn_ds = new YAHOO.util.DataSource(tmpArray);
					dsn_ds.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
					dsn_ds.responseSchema = {fields:["models"]};
					
				var dsn_name_ac = new YAHOO.widget.AutoComplete("model_name","mdl_suggest_list",dsn_ds);
			},
			handleFailure:function (o) {
				alert ('Server cannot find a list of Models');
			},
			processResult: function (o){
				alert ('result process');
			},
			startRequest:function () {
				YAHOO.util.Connect.asyncRequest('POST','./gears/ServiceInterface.cfm?method=getAvailableModels', callback_MDLs, 'ContextName='+YAHOO.util.Dom.get('context_name').value);	
			}
		}
		var callback_MDLs = {
			success:MDL_AutoComplete.handleSuccess,
			failure:MDL_AutoComplete.handleFailure,
			scope:MDL_AutoComplete,
			timeout: app_timeout 
		};
		
	MDL_AutoComplete.startRequest();
	/*
	YAHOO.util.Event.on(YAHOO.util.Dom.get('context_name'), "blur", function () {
		if (YAHOO.util.Dom.get('context_name').value.length > 0) {
			MDL_AutoComplete.startRequest();
		}	
	});
	*/
	
	
	
	var DSN_AutoComplete = {
		handleSuccess:function (o) {
			var tmpArray = o.responseText.replace(/[\s\t\n\r]/,"").split(",");
			var dsn_ds = new YAHOO.util.DataSource(tmpArray);
				dsn_ds.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
				dsn_ds.responseSchema = {fields:["dsn"]};
				
			var dsn_name_ac = new YAHOO.widget.AutoComplete("dsn_name","dsn_suggest_list",dsn_ds);
		},
		handleFailure:function (o) {
			alert ('Server cannot find a list of DSNs');
		},
		processResult: function (o){
			alert ('result process');
		},
		startRequest:function () {
			YAHOO.util.Connect.asyncRequest('POST','./gears/ServiceInterface.cfm', callback_DSNs, 'method=getAvailableDSNs');	
		}
	}
	var callback_DSNs = {
		success:DSN_AutoComplete.handleSuccess,
		failure:DSN_AutoComplete.handleFailure,
		scope:DSN_AutoComplete,
		timeout: app_timeout 
	};
	
	DSN_AutoComplete.startRequest();

	
	var CONTEXTS_AutoComplete = {
		handleSuccess:function (o) {
			var tmpArray = o.responseText.replace(/[\s\t\n\r]/,"").split(",");
			var context_ds = new YAHOO.util.DataSource(tmpArray);
				context_ds.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
				context_ds.responseSchema = {fields:["context"]};
				
			var context_name_ac = new YAHOO.widget.AutoComplete("context_name","context_suggest_list",context_ds);
		},
		handleFailure:function (o) {
			alert ('ERROR: Server cannot find a list of contexts');
		},
		processResult: function (o){
			alert ('result process');
		},
		startRequest:function () {
			YAHOO.util.Connect.asyncRequest('POST','./gears/ServiceInterface.cfm', callback_CTXs, 'method=getAvailableContexts');
			
				
		}
	}
	var callback_CTXs = {
		success:CONTEXTS_AutoComplete.handleSuccess,
		failure:CONTEXTS_AutoComplete.handleFailure,
		scope:CONTEXTS_AutoComplete,
		timeout: app_timeout 
	};
	
	CONTEXTS_AutoComplete.startRequest();
	
	RefreshDSN = new YAHOO.widget.Button("refresh_dsn",{
		type:"button",
		label:"DSNs"
	});
	
	
	RefreshContexts = new YAHOO.widget.Button("refresh_ctx",{
		type:"button",
		label:"Contexts"
	});
	
	RefreshModels = new YAHOO.widget.Button("refresh_mdl",{
		type:"button",
		label:"Models"
	});
	try {
		RefreshDSN.addListener("click",DSN_AutoComplete.startRequest);
		RefreshContexts.addListener("click",CONTEXTS_AutoComplete.startRequest);
		RefreshModels.addListener("click",MDL_AutoComplete.startRequest);
	}
	catch (err) {
		
		// do nothing
	}
	var setValues = function (p_sType, p_aArgs, p_oItem) {
		db_env_button.set("label",p_oItem.cfg.getProperty("text")); 
		db_env_button.set("value",p_oItem.value);
	}
	
	var db_menu = [
		{text:"SQLite*",value:"sqlite", onclick:{fn:setValues }},
		{text:"MySQL",value:"mysql", onclick:{fn:setValues }},
		{text:"MS SQL Server",value:"mssql", onclick:{fn:setValues }}
	]
	db_env_button = new YAHOO.widget.Button("db-vendor-info",{
			type: "split", 
			menu:db_menu,
			label:"SQLite*",
			value:"sqlite"
	});
});

YAHOO.util.Event.onContentReady("modelbuilder-form",function () {
	var idButton = new YAHOO.widget.Button("model-id-gen",{
		id:"ID",
		type:"button",
		label:"Create 'ID'"
	});
	
		
	idButton.on("click", function (){
	var temp_array = [];
		temp_array.push({
			db_field_name:"id",
			db_field_mapping:"",
			db_field_datatype:"integer",
			db_field_length:"",
			db_field_default:"",
			db_field_isPrimaryKey:true,
			db_field_isIdentity:false,
			db_field_isForeignKey:false,
			db_field_refers_table:"",
			db_field_refers_column:"",
			db_field_allowNull:false,
			db_field_isUnique:false
		});
		tbl.addRow(temp_array[0],0);
	});
	
	var createdDateButton = new YAHOO.widget.Button("model-created_date-gen",{
		id:"ID",
		type:"button",
		label:"Create 'Created Date'"
	});
	
	createdDateButton.on("click", function (){
		var temp_array = [];
		temp_array.push({
			db_field_name:"created_date",
			db_field_mapping:"",
			db_field_datatype:"datetime",
			db_field_length:"",
			db_field_default:"current_timestamp",
			db_field_isPrimaryKey:false,
			db_field_isIdentity:false,
			db_field_isForeignKey:false,
			db_field_refers_table:"",
			db_field_refers_column:"",
			db_field_allowNull:false,
			db_field_isUnique:false
		});
		
		tbl.addRow(temp_array[0],tbl.getRecordSet()._records.length);
	});
	
	var updatedDateButton = new YAHOO.widget.Button("model-updated_date-gen",{
		id:"ID",
		type:"button",
		label:"Create 'Updated Date'"
	});
	
	updatedDateButton.on("click", function (){
		var temp_array = [];
		temp_array.push({
			db_field_name:"updated_date",
			db_field_mapping:"",
			db_field_datatype:"datetime",
			db_field_length:"",
			db_field_default:"current_timestamp",
			db_field_isPrimaryKey:false,
			db_field_isIdentity:false,
			db_field_isForeignKey:false,
			db_field_refers_table:"",
			db_field_refers_column:"",
			db_field_allowNull:false,
			db_field_isUnique:false
		});
		
		tbl.addRow(temp_array[0],tbl.getRecordSet()._records.length);
	});
	
	var isActiveButton = new YAHOO.widget.Button("model-is_active-gen",{
		id:"ID",
		type:"button",
		label:"Create 'Is Active'"
	});
	
	isActiveButton.on("click", function (){
		var temp_array = [];
		temp_array.push({
			db_field_name:"is_active",
			db_field_mapping:"",
			db_field_datatype:"bit",
			db_field_length:"",
			db_field_default:"true",
			db_field_isPrimaryKey:false,
			db_field_isIdentity:false,
			db_field_isForeignKey:false,
			db_field_refers_table:"",
			db_field_refers_column:"",
			db_field_allowNull:false,
			db_field_isUnique:false
		});
		
		tbl.addRow(temp_array[0],tbl.getRecordSet()._records.length);
	});
	
	var columnButton = new YAHOO.widget.Button("model-column-gen",{
		id:"add_column",
		type:"button",
		label:"Add Column"
	});
	
	columnButton.on("click", function (){
		var temp_array = [];	
		temp_array.push({
				db_field_name:"",
				db_field_datatype:"",
				db_field_length:"",
				db_field_default:"",
				db_field_isPrimaryKey:false,
				db_field_isIdentity:false,
				db_field_isForeignKey:false,
				db_field_refers_table:"",
				db_field_refers_column:"",
				db_field_allowNull:false,
				db_field_isUnique:false
			});
		tbl.addRow(temp_array[0],tbl.getRecordSet()._records.length);
	});
});





YAHOO.util.Event.onContentReady("modelbuilder-datatable", function () {
	YAHOO.widget.DataTable.deleteButtonFormatter = function (elLiner, oRecord, oColumn, oData) {
		elLiner.innerHTML = '<img src="images/icons/cancel.png" label="delete" alt="delete row" />';
	}
	
	col_defs = [
	{key:"db_field_delete",label:"&nbsp;",formatter:YAHOO.widget.DataTable.deleteButtonFormatter, width:"35px"},
		{key:"db_field_name",label:"Field Name",sortable:true,editor:new YAHOO.widget.TextboxCellEditor({disableBtns:true})},
		{key:"db_field_datatype",label:"Data Type",
			editor: new YAHOO.widget.DropdownCellEditor({dropdownOptions:["integer","varchar","datetime","decimal","bit","text"],disableBtns:false})},
		{key:"db_field_length",label:"Length",editor:new YAHOO.widget.TextboxCellEditor({disableBtns:true}),sortable:true},
		{key:"db_field_default",label:"Default Value",editor:new YAHOO.widget.TextboxCellEditor({disableBtns:true}),sortable:true},
		{key:"db_field_isPrimaryKey",label:"Primary Key",formatter:"radio",sortable:true},
		{key:"db_field_isIdentity",label:"Identity",formatter:"checkbox", sortable:true},
		{key:"db_field_isForeignKey",label:"Foreign Key",formatter:"checkbox",sortable:true},
		{key:"db_field_refers_table",label:"Refers Table",editor:new YAHOO.widget.TextboxCellEditor({disableBtns:true}),sortable:true},
		{key:"db_field_refers_column",label:"Foreign Key Column",editor:new YAHOO.widget.TextboxCellEditor({disableBtns:true}),sortable:true},
		{key:"db_field_allowNull",label:"Allow Nulls",formatter:"checkbox",sortable:true},
		{key:"db_field_isUnique",label:"Unique",formatter:"checkbox",sortable:true},
		{key:"db_field_mapping",label:"Display Mapping",editor:"textbox",sortable:true,editor:new YAHOO.widget.TextboxCellEditor({disableBtns:true})}
	];


	ds = new YAHOO.util.DataSource([]);
	ds.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
	ds.responseSchema = {fields:["db_field_name","db_field_datatype","db_field_length","db_field_default","db_field_isPrimaryKey","db_field_isForeignKey"]};
		
	tbl = new YAHOO.widget.DataTable("modelbuilder-datatable",col_defs,ds,{
		draggableColumns:true,
		selectionMode:'singleCell'
	});
	
	tbl.subscribe("rowMouseoverEvent", tbl.onEventHighlightRow);
	tbl.subscribe("rowMouseoutEvent", tbl.onEventUnhighlightRow);
	tbl.subscribe("cellClickEvent", tbl.onEventSelectRow);
	tbl.subscribe("cellClickEvent", tbl.onEventShowCellEditor);
	
	
	tbl.subscribe("radioClickEvent", function (oArgs){		
		for (var i=0;i<tbl.getRecordSet()._records.length;i++){
			tbl.getRecordSet()._records[i]._oData.db_field_isPrimaryKey = false;
			tbl.getRecordSet()._records[i]._oData.db_field_isIdentity = false;
			tbl.getRecordSet()._records[i]._oData.db_field_isForeignKey = false;
			tbl.getRecordSet()._records[i]._oData.db_field_allowNull = false;
			tbl.getRecordSet()._records[i]._oData.db_field_isUnique = false;
		}
		
		for (j=0;j<YAHOO.util.Dom.getElementsByClassName('yui-dt-checkbox').length;j++){
			YAHOO.util.Dom.getElementsByClassName('yui-dt-checkbox')[j].checked = false;
		}
		
		if (this.getRecord(oArgs.target).getData("db_field_isForeignKey") == false) {
			oArgs.target.checked = true;
			this.getRecord(oArgs.target).setData("db_field_isPrimaryKey",oArgs.target.checked);	
		}
		else {
			alert ("You cannot set this column as 'Primary Key'. This column is set as a 'Foreign Key'");
			oArgs.target.checked = false;
		}
	});

	tbl.subscribe("editorSaveEvent", function (oArgs){
		if (oArgs.editor.getColumn().key == "db_field_datatype") 
		{
			tbl.updateCell(oArgs.editor.getRecord(),"db_field_length","");
			tbl.updateCell(oArgs.editor.getRecord(),"db_field_default","");
			tbl.updateCell(oArgs.editor.getRecord(),"db_field_isIdentity", false);
			tbl.updateCell(oArgs.editor.getRecord(),"db_field_length","");
			tbl.updateCell(oArgs.editor.getRecord(),"db_field_default","");
		}
		
		switch (oArgs.editor.getColumn().key) 
		{
			case "db_field_length":
			case "db_field_default":
				switch (oArgs.editor.getRecord().getData("db_field_datatype"))
				{
					case "varchar":
						//do nothing
					break;
					case "decimal":
						// do nothing
					break;
					case "datetime":
						// do nothing
					break;
					default:
						alert("Default value cannot be saved. Change the datatype for this column to use 'varchar'. In case you select the 'decimal' datatype, provide scale here");
						tbl.updateCell(oArgs.editor.getRecord(),"db_field_length");
						tbl.updateCell(oArgs.editor.getRecord(),"db_field_default");
					break;
				}
			break;
		}
				
		if (oArgs.editor.getColumn().key == "db_field_refers_table") 
		{
			if (oArgs.editor.getRecord().getData("db_field_isForeignKey") == false)
			{
				alert("Reference table cannot be added when the column is not a foreign key");
				tbl.updateCell(oArgs.editor.getRecord(),"db_field_refers_table");
				tbl.updateCell(oArgs.editor.getRecord(),"db_field_refers_column");
			}
		}
		
		if (oArgs.editor.getColumn().key == "db_field_refers_column") {
			if (oArgs.editor.getRecord().getData("db_field_isForeignKey") == false)
			{
				alert("Reference table cannot be added when the column is not a foreign key");
				tbl.updateCell(oArgs.editor.getRecord(),"db_field_refers_table");
				tbl.updateCell(oArgs.editor.getRecord(),"db_field_refers_column");
			}
		}
	});
		
	tbl.subscribe("checkboxClickEvent", function (oArgs){	
		if (this.getColumn(oArgs.target).key == "db_field_isIdentity") {
			if (this.getRecord(oArgs.target).getData("db_field_isPrimaryKey") == true) {
				if (this.getRecord(oArgs.target).getData("db_field_datatype") == "integer") {
					this.getRecord(oArgs.target).setData("db_field_isIdentity",oArgs.target.checked);	
				}
				else {
					alert ("Please select 'integer' data type for setting this column as an identity or auto_increment key");
					oArgs.target.checked = false;
				}
			}
			else {
				alert ("Only a 'Primary Key' column with 'integer' datatype can be set to be identity or auto_increment type");
				oArgs.target.checked = false;
			}
		}
		
		if (this.getColumn(oArgs.target).key == "db_field_isForeignKey") {
			if (this.getRecord(oArgs.target).getData("db_field_isPrimaryKey") == true) {
				tbl.updateCell(this.getRecord(oArgs.target),"db_field_isPrimaryKey",false);
				tbl.updateCell(this.getRecord(oArgs.target),"db_field_isIdentity","");
			}
			
			this.getRecord(oArgs.target).setData("db_field_isForeignKey",oArgs.target.checked);	
			
			if (this.getRecord(oArgs.target).getData("db_field_isForeignKey") == false) {
				//alert ('You have changed the foreign key constraint. The references to FK tables will be removed');
				tbl.updateCell(this.getRecord(oArgs.target),"db_field_refers_table","");
				tbl.updateCell(this.getRecord(oArgs.target),"db_field_refers_column","");
			}
		}
		
		
		if (this.getColumn(oArgs.target).key == "db_field_allowNull") {
			if ((this.getRecord(oArgs.target).getData("db_field_isPrimaryKey") || this.getRecord(oArgs.target).getData("db_field_isPrimaryKey"))) {
				alert ("This is set to be either a 'Key' column. Nulls cannot be allowed");
				oArgs.target.checked = false;
			}
			else {
				this.getRecord(oArgs.target).setData("db_field_allowNull",oArgs.target.checked);
			}
		}
		
		if (this.getColumn(oArgs.target).key == "db_field_isUnique") {
			if (this.getRecord(oArgs.target).getData("db_field_isPrimaryKey")) {
				alert ("This column is set to be a 'Primary Key' column. Unique constraint cannot be applied on this column");
				oArgs.target.checked = false;
			}
			else {
				this.getRecord(oArgs.target).setData("db_field_isUnique",oArgs.target.checked);
				if (this.getRecord(oArgs.target).getData("db_field_default").length > 0) {
					alert("You have set a 'unique' constraint on column with a default value. The default value will be cleared");
					this.updateCell(this.getRecord(oArgs.target),"db_field_default","");
				}
			}
		}
	});
	
	tbl.subscribe("cellClickEvent", function (oArgs){
		var target = YAHOO.util.Event.getTarget(oArgs);
		
		if(this.getColumn(target).key == "db_field_delete"){
			tbl.deleteRow(target);
		}
	});
});

YAHOO.util.Event.onDOMReady(function () {
	YAHOO.util.Event.on(YAHOO.util.Dom.get('cp_tbl_2_mdl'), "click", function () { 
		YAHOO.util.Dom.get('model_name').value = YAHOO.util.Dom.get('table_name').value;
	});
	
	YAHOO.util.Event.on(YAHOO.util.Dom.get('cp_mdl_2_tbl'), "click", function () {
		YAHOO.util.Dom.get('table_name').value = YAHOO.util.Dom.get('model_name').value;
	});
})


// Reverse Engineer from Model
YAHOO.util.Event.onContentReady("model-reverse-eng",function () {
	var revEng = new YAHOO.widget.Button("model-reverse-eng",{
		label:"Reverse Engineer"
	});
	
	
	revEng.on("click", function () {
		if (YAHOO.util.Dom.get('model_name').value.length == 0 || YAHOO.util.Dom.get('context_name').value.length == 0)
		{
			alert ("Model Name and Context/Application name is required to reverse engineer the datatable.");
			return;
			
		}
		
		var ReverseEnggReq = {
			handleSuccess:function (o) {
				try {
						var tempArr = YAHOO.lang.JSON.parse(o.responseText);
					}
					catch(err) {
						alert("Error occurred while parsing incoming JSON data from server. Please check incoming JSON for inconsistencies");
					}
					
					for (var i=0;i<tempArr.length;i++) {
						tbl.addRow(tempArr[i], i);
					}
				},
				handleFailure:function (o) {
					alert ('There was an error in processing your request');
				},
				processResult: function (o){
					alert ('result process');
				},
				startRequest:function () {
					// empty data table first
					for (var j=tbl.getRecordSet()._records.length;j>=0;j--) {
						tbl.deleteRow(j);
					}
					
					YAHOO.util.Connect.asyncRequest('POST','./gears/ServiceInterface.cfm?method=reverseEngineer',callback_reverseenggreq,
						'context_name='+YAHOO.util.Dom.get("context_name").value +
						'&model_name='+YAHOO.util.Dom.get("model_name").value);
					
					
						
				}
			};
		var callback_reverseenggreq = {
			success:ReverseEnggReq.handleSuccess,
			failure:ReverseEnggReq.handleFailure,
			scope:ReverseEnggReq,
			timeout: app_timeout 
		};
		
		ReverseEnggReq.startRequest();		
	});
});


	YAHOO.util.Event.onContentReady("get_migrations", function () {
		
		var GetMigrations = {
				handleSuccess:function (o) {
					var tempArr = new Array();
					try {
						var tempArr = YAHOO.lang.JSON.parse(o.responseText);
					}
					catch(err) {
						alert("Error occurred while parsing incoming JSON data from server. Please check incoming JSON for inconsistencies");
					}
					
					// fill datatable with newly found rows
					for (var i=0;i<tempArr.length;i++) {
						//alert (i + " " + tempArr[i]);
						migration_tbl.addRow(tempArr[i], i);
					}
					wait_dialog.hide(); 
					
				},
				handleFailure:function (o) {
					wait_dialog.hide(); 
					alert ('Server cannot find a list of Migrations');
				},
				processResult: function (o){
					wait_dialog.hide(); 
					alert ('result process');
				},
				startRequest:function () {
					wait_dialog.show(); 
					//empty datatable first
					//alert(migration_tbl.getRecordSet()._records.length);
					for (var j=migration_tbl.getRecordSet()._records.length;j>=0;j--) {
						migration_tbl.deleteRow(j);
					}
					
					YAHOO.util.Connect.asyncRequest('POST','./gears/ServiceInterface.cfm', callback_migrations, 'method=getMigrations&ContextName='+YAHOO.util.Dom.get('context_name').value);	
				}
			}
			var callback_migrations = {
				success:GetMigrations.handleSuccess,
				failure:GetMigrations.handleFailure,
				scope:GetMigrations,
				timeout: app_timeout 
			};
		
		var getMigrationsBtn = new YAHOO.widget.Button("get_migrations", {
			label:"Get Migration Files"
		});
		getMigrationsBtn.on("click", function () {
			
			GetMigrations.startRequest();
		});
	});
	
YAHOO.util.Event.onDOMReady(function () {
// Initialize the temporary Panel to display while waiting for external content to load
	YAHOO.widget.DataTable.upButtonFormatter = function (elLiner, oRecord, oColumn, oData) {
		elLiner.innerHTML = '<img src="images/icons/accept.png" title="Create Table" alt="delete row" style="cursor:hand;" />';
	}
	
	YAHOO.widget.DataTable.downButtonFormatter = function (elLiner, oRecord, oColumn, oData) {
		elLiner.innerHTML = '<img src="images/icons/delete.png" title="Drop Table" alt="delete row" style="cursor:hand;" />';
	}
	
	
	var migration_col_defs = [
		{key:"db_field_up",label:"Create",formatter:YAHOO.widget.DataTable.upButtonFormatter, width:"35px"},
		{key:"db_field_down",label:"Drop",formatter:YAHOO.widget.DataTable.downButtonFormatter, width:"35px"},
		{key:"db_migration_name",label:"Available Migrations",sortable:true}
	];

	var migration_ds = new YAHOO.util.DataSource([]);
		migration_ds.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
		
	migration_tbl = new YAHOO.widget.DataTable("migrations-container",migration_col_defs,migration_ds,{
			draggableColumns:true,
			selectionMode:'singleCell',
			caption:"Database Migrations",
			width:"600px"
		});
	
	
	var migration_name,migration_action;
		
		migration_tbl.subscribe("cellClickEvent", function (oArgs) {
			if (this.getColumn(oArgs.target).key == "db_field_up")  {
				migration_name = this.getRecord(oArgs.target).getData("db_migration_name");
				migration_action = "up";
				if (confirm("Confirm Action: Click 'Ok' to create table, 'Cancel' to cancel this action.")) {
					RunMigrations.startRequest(1,2);
				}
				
			}
			
			else if (this.getColumn(oArgs.target).key == "db_field_down")  {
				migration_name = this.getRecord(oArgs.target).getData("db_migration_name");
				migration_action = "down";
				if (confirm("Confirm Action: Click 'Ok' to drop table, 'Cancel' to cancel this action.")) {
					RunMigrations.startRequest();
				}
			}
	});
		
		
		
		var RunMigrations = {
			handleSuccess:function (o) {
					wait_dialog.hide();
					try {
						var tempArr = YAHOO.lang.JSON.parse(o.responseText);
						YAHOO.util.Dom.get('stacktrace').innerHTML = tempArr[0]["stacktrace"];
						alert("Result: " + tempArr[0]["result"] + "\n" + "Message: " +tempArr[0]["message"]+ "\n" + "Detail: " +tempArr[0]["detail"]);
					}
					catch(err) {
						alert("Error occurred while parsing incoming JSON data from server. Please check incoming JSON for inconsistencies.\n" +
								"The utility YAHOO.lang.JSON.parse will not parse json correctly if domain used is not localhost. " +
								"Please review the response text in the stacktrace textarea below.");
						YAHOO.util.Dom.get('stacktrace').innerHTML = err.message + "\n\r" + o.responseText ;					
					}
					
				},
				handleFailure:function (o) {
					wait_dialog.hide();
					alert ('Server cannot failed to run the selected migration. Please check stacktrace for source of error.');
				},
				processResult: function (o){
					wait_dialog.hide(); 
					alert ('result process');
				},
				startRequest:function () {
					
					
					YAHOO.util.Connect.asyncRequest('POST','./gears/ServiceInterface.cfm', callback_run_migrations, 
						'method=RunMigrations' +
						'&dsn_name='+YAHOO.util.Dom.get('dsn_name').value +
						'&ContextName='+YAHOO.util.Dom.get('context_name').value +
						'&MigrationName='+migration_name +
						'&MigrationAction='+migration_action
					);
					
					wait_dialog.show(); 
						
				}
			}
			
			var callback_run_migrations = {
				success:RunMigrations.handleSuccess,
				failure:RunMigrations.handleFailure,
				scope:RunMigrations,
				timeout:  app_timeout
		};
		
});